package controller

import (
	"image-server/middleware"
	response "image-server/models"
	"image-server/models/dto"
	service "image-server/services"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// AlbumController 相册控制器，处理与相册相关的HTTP请求
type AlbumController struct {
	albumService *service.AlbumService // 相册服务层实例，用于业务逻辑处理
}

// NewAlbumController 创建AlbumController实例
func NewAlbumController(albumService *service.AlbumService) *AlbumController {
	return &AlbumController{albumService: albumService}
}

// CreateAlbum 创建相册
// 请求方式：POST
// 功能：验证用户身份后，根据请求参数创建新相册
func (c *AlbumController) CreateAlbum(ctx *gin.Context) {
	// 获取当前登录用户
	user, err := middleware.GetUser(ctx)
	if err != nil || user == nil {
		response.Error(ctx.Writer, http.StatusUnauthorized, "未授权访问")
		return
	}
	// 绑定并验证请求参数
	var req struct {
		Name        string `json:"name" binding:"required,max=50"` // 相册名称
		Description string `json:"description"`
		IsPublic    bool   `json:"is_public"` // 是否公开
	}
	if err := ctx.ShouldBindJSON(&req); err != nil {
		response.Error(ctx.Writer, http.StatusBadRequest, "参数错误：请检查相册名称")
		return
	}
	// 调用服务层创建相册-一定要传递user
	album, err := c.albumService.CreateAlbum(user, req.Name, req.Description, req.IsPublic)
	if err != nil {
		response.Error(ctx.Writer, http.StatusInternalServerError, service.ParseError(err))
		return
	}
	// 返回成功响应
	response.Success(ctx.Writer, album, "创建成功")
}

// GetUserAlbums 获取用户相册列表
// 请求方式：GET
// 功能：获取当前登录用户的相册列表，支持分页
func (c *AlbumController) GetUserAlbums(ctx *gin.Context) {
	// 1. 获取当前登录用户
	user, err := middleware.GetUser(ctx)
	if err != nil || user == nil {
		response.Error(ctx.Writer, http.StatusUnauthorized, "未授权访问")
		return
	}

	// 2. 解析分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(ctx.DefaultQuery("limit", "10"))

	// 3. 调用服务层获取相册列表
	albums, total, err := c.albumService.GetUserAlbums(user.ID, page, limit)
	if err != nil {
		response.Error(ctx.Writer, http.StatusInternalServerError, service.ParseError(err))
		return
	}

	// 4. 构建分页响应数据
	data := gin.H{
		"albums": albums,
		"pagination": gin.H{
			"total": total,
			"page":  page,
			"limit": limit,
			"pages": (total + int64(limit) - 1) / int64(limit), // 总页数计算
		},
	}

	// 5. 返回成功响应
	response.Success(ctx.Writer, data)
}

// DeleteAlbum 删除相册
// 请求方式：DELETE
// 功能：验证用户身份后，根据相册ID删除指定相册
func (c *AlbumController) DeleteAlbum(ctx *gin.Context) {
	// 1. 获取当前登录用户
	user, err := middleware.GetUser(ctx)
	if err != nil || user == nil {
		response.Error(ctx.Writer, http.StatusUnauthorized, "未授权访问")
		return
	}

	// 2. 解析相册ID
	albumID, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil {
		response.Error(ctx.Writer, http.StatusBadRequest, "无效的相册ID")
		return
	}

	// 3. 调用服务层删除相册
	if err := c.albumService.DeleteAlbum(albumID, user.ID); err != nil {
		response.Error(ctx.Writer, http.StatusInternalServerError, service.ParseError(err))
		return
	}

	// 4. 返回成功响应
	response.Success(ctx.Writer, nil, "删除成功")
}

// GetAlbumDetail 获取相册详情
// 请求方式：GET
// 功能：根据相册ID获取相册详情，验证访问权限
func (c *AlbumController) GetAlbumDetail(ctx *gin.Context) {
	// 1. 解析相册ID
	albumID, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil {
		response.Error(ctx.Writer, http.StatusBadRequest, "无效的相册ID")
		return
	}

	// 2. 获取当前用户ID（未登录则为0）
	user, _ := middleware.GetUser(ctx)
	userID := int64(0)
	if user != nil {
		userID = user.ID
	}

	// 3. 调用服务层获取相册详情
	album, err := c.albumService.GetAlbumByID(albumID, userID)
	if err != nil {
		msg := service.ParseError(err)
		switch msg {
		case "相册不存在":
			response.Error(ctx.Writer, http.StatusNotFound, msg)
		case "无权访问":
			response.Error(ctx.Writer, http.StatusForbidden, msg)
		default:
			response.Error(ctx.Writer, http.StatusInternalServerError, msg)
		}
		return
	}

	// 4. 返回相册详情
	response.Success(ctx.Writer, album)
}

// UpdateAlbum 更新相册
// 请求方式：PUT
// 功能：验证用户身份后，根据请求参数更新相册信息
func (c *AlbumController) UpdateAlbum(ctx *gin.Context) {
	// 1. 解析相册ID
	albumID, err := strconv.ParseInt(ctx.Param("id"), 10, 64)
	if err != nil {
		response.Error(ctx.Writer, http.StatusBadRequest, "无效的相册ID")
		return
	}
	// 2. 获取当前登录用户
	user, err := middleware.GetUser(ctx)
	if err != nil || user == nil {
		response.Error(ctx.Writer, http.StatusUnauthorized, "未授权访问")
		return
	}

	// 3. 绑定请求参数
	var req dto.UpdateAlbumRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		response.Error(ctx.Writer, http.StatusBadRequest, "参数错误")
		return
	}

	// 4. 调用服务层更新相册
	album, err := c.albumService.UpdateAlbum(albumID, user.ID, user.WpsUID, req.Name, req.IsPublic)
	if err != nil {
		response.Error(ctx.Writer, http.StatusInternalServerError, service.ParseError(err))
		return
	}

	// 5. 返回更新后的相册信息
	response.Success(ctx.Writer, album, "更新成功")
}

// GetUserPublicAlbums 查询指定用户的公开相册列表
// 请求方式：GET
// 路径参数：user_id - 目标用户ID
// 查询参数：page - 页码（默认1），limit - 每页条数（默认10）
func (c *AlbumController) GetUserPublicAlbums(ctx *gin.Context) {
	// 1. 解析路径参数（目标用户ID）
	targetUserID, err := strconv.ParseInt(ctx.Param("user_id"), 10, 64)
	if err != nil {
		response.Error(ctx.Writer, http.StatusBadRequest, "无效的用户ID")
		return
	}

	// 2. 解析分页参数
	page, _ := strconv.Atoi(ctx.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(ctx.DefaultQuery("limit", "10"))

	// 3. 调用服务层查询公开相册
	albums, total, err := c.albumService.GetPublicAlbumsByUserID(targetUserID, page, limit)
	if err != nil {
		response.Error(ctx.Writer, http.StatusInternalServerError, service.ParseError(err))
		return
	}

	// 4. 构建分页响应
	data := gin.H{
		"albums": albums,
		"pagination": gin.H{
			"total": total,
			"page":  page,
			"limit": limit,
			"pages": (total + int64(limit) - 1) / int64(limit),
		},
	}
	response.Success(ctx.Writer, data)
}
